package main

import (
	"fmt"
	"log"
	"os"
	"path"
)

// Transport saver file transport
type Transport struct {
	Name string // Name file name
	Data []byte // Data file data
}

// Saver save images in directory
type Saver struct {
	parentDir string
	path      string
	transport chan Transport
	exit      chan struct{}
}

func NewSaver(dir string, transport chan Transport, exit chan struct{}) *Saver {
	return &Saver{
		parentDir: dir,
		path:      dir,
		transport: transport,
		exit:      exit,
	}
}

func (s *Saver) CreateDir(dirName string) error {
	if dirName == "" {
		return fmt.Errorf("empty dir name")
	}

	s.path = path.Join(s.parentDir, dirName)
	if err := os.Mkdir(s.path, os.ModeDir); err != nil {
		return fmt.Errorf("make dir failed: %w", err)
	}
	return nil
}

func (s *Saver) Receive() {
	for {
		select {
		case trans := <-s.transport:
			s.save(trans)
		case <-s.exit:
			return
		}
	}
}

func (s *Saver) save(trans Transport) {
	if trans.Name == "" || len(trans.Data) == 0 {
		return
	}
	if err := os.WriteFile(path.Join(s.path, trans.Name), trans.Data, 0600); err != nil {
		log.Printf("write file=%s failed: %v", trans.Name, err)
	}
}
